<template>
  <div>
    <div class="baseInfo infoBox">
      <FormTitle titleName="基础信息" style="margin-bottom: 16px;"></FormTitle>
      <el-form :model="form" :label-suffix="isView ? ':' : ''" :hide-required-asterisk="isView" :rules="baseInfoFormRules" ref="formRef" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品编号" required>
              <el-input v-if="!isView" :disabled="true" class="formWidth" v-model="form.code" placeholder="保存后自动生成"></el-input>
              <span v-else>{{ form.code }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="类别">
              <el-select v-if="!isView" v-model="form.type" filterable placeholder="请选择" class="formWidth">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <span v-else>{{ categoryLabel || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="brand" label="经营品牌">
              <el-select v-if="!isView" v-model="form.brand" multiple filterable collapse-tags collapse-tags-tooltip placeholder="请选择"
                class="formWidth">
                <el-option v-for="brand in brandOptions" value-key="value" :key="brand.value" :label="brand.label"
                  :value="brand.value"></el-option>
              </el-select>
              <span v-else>{{ formatBrand(form.brand) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="name" label="产品名称">
              <el-input v-if="!isView" class="formWidth" @blur="nameBlur" @input="nameInput" :maxlength="50" v-model.trim="form.name"
                placeholder="请输入"></el-input>
              <span v-else>{{ form.name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="条码">
              <el-input v-if="!isView" class="formWidth" v-model.trim="form.barCode" placeholder="请输入"></el-input>
              <span v-else>{{ form.barCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="mnemonicCode" label="助记码">
              <el-input v-if="!isView" class="formWidth" v-model.trim="form.mnemonicCode" placeholder="请输入"></el-input>
              <span v-else>{{ form.mnemonicCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品规格">
              <el-input v-if="!isView" class="formWidth" :maxlength="50" v-model.trim="form.specification" placeholder="请输入"></el-input>
              <span v-else>{{ form.specification }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位">
              <el-select v-if="!isView" v-model="form.unit" filterable placeholder="请选择" class="formWidth">
                <el-option v-for="unit in unitOptions" :key="unit.value" :label="unit.label"
                  :value="unit.value"></el-option>
              </el-select>
              <span v-else>{{ form.unit }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产地">
              <el-input v-if="!isView" class="formWidth" :maxlength="50" v-model.trim="form.placeOrigin" placeholder="请输入"></el-input>
              <span v-else>{{ form.placeOrigin }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="生产厂家">
              <el-input v-if="!isView" class="formWidth" :maxlength="50" v-model.trim="form.manufacturer" placeholder="请输入"></el-input>
              <span v-else>{{ form.manufacturer }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="执行标准">
              <el-input v-if="!isView" class="formWidth" :maxlength="50" v-model.trim="form.executiveStandard" placeholder="请输入"></el-input>
              <span v-else>{{ form.executiveStandard }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产品图片">
              <div v-if="!isView">
                <UploadImg :imageListUrlInfo="form.imgs" :multiple="true" @backValue="backValueImg">
                </UploadImg>
                <div class="tips">支持jpg、jpeg、png格式；图片比例1:1；建议为300*300；最多5张；单张不超过5M</div>
              </div>
              <div v-else class="imgBox">
                <template v-if="form.imgs.length">
                  <el-image 
                  class="imgItemBox" 
                  v-for="(item,index) in form.imgs" 
                  :key="index" 
                  :src="item"
                  :preview-src-list="form.imgs"
                  :initial-index="index"
                  fit="contain"
                ></el-image>
                </template>
                <el-image v-else class="imgItemBox" fit="contain" :preview-src-list="['https://static.91medicine.net/jiuyang/img/404.png']" :src="'https://static.91medicine.net/jiuyang/img/404.png'"></el-image>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="销售状态" prop="salesStatus" style="margin-top: 16px;">
              <div v-if="!isView">
                <el-radio-group v-model="form.salesStatus" @change="changeSalesStatus">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="2">停售</el-radio>
                </el-radio-group>
                <div class="tips" style="margin-top: -10px;">设置针对经营该商品的所有门店生效</div>
              </div>
              <span v-else>{{form.salesStatus === 1 ? '正常':'停售'}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售分类" prop="salesClassification">
              <div v-if="!isView">
                <el-select v-model="form.salesClassification" multiple filterable collapse-tags collapse-tags-tooltip
                  placeholder="请选择">
                  <el-option v-for="item in salesClassOptions" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
                <div class="tips">门店线上线下销售商品时，展示在商城和收银台的分类</div>
              </div>
              <span v-else>{{ salesClassLabel || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="零售价" prop="retailPrice">
              <el-input 
                v-if="!isView" 
                class="formWidth" 
                v-model.trim="form.retailPrice" 
                placeholder="请输入" 
                @input="()=>{form.retailPrice=limitFloat(form.retailPrice)}" 
                @blur="blurRetailPrice"
              />
              <span v-else>{{ form.retailPrice }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最新进价" >
              <el-input v-if="!isView" class="formWidth" v-model.trim="form.latestPurchasePrice" placeholder="请输入"
                @input="()=>{form.latestPurchasePrice=limitFloat(form.latestPurchasePrice)}" 
                @blur="()=>{form.latestPurchasePrice=giveFloatMin(form.latestPurchasePrice)}"
              />
              <span v-else>{{ form.latestPurchasePrice }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="最低售价" prop="minSellingPrice" :rules="minSalePriceRules(form.retailPrice)">
              <div v-if="!isView">
                <el-input 
                class="formWidth"  
                @blur="()=>{form.minSellingPrice=giveFloatMin(form.minSellingPrice)}"
                @input="()=>{form.minSellingPrice=limitFloat(form.minSellingPrice)}" 
                 v-model.trim="form.minSellingPrice"
                 placeholder="请输入"
                 ></el-input>
                <div class="tips">门店线上线下销售商品时，商品改价不得低于最低售价</div>
              </div>
              <span v-else>{{ form.minSellingPrice || '-' }}</span>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="用法用量">
              <el-table :data="tableData" border style="width: 100%;" :header-cell-style="{ 'background-color': '#DDD' }">
                <el-table-column prop="totalDose" label="总剂量">
                  <template v-slot="{ row }">
                    <el-input v-if="!isView" :maxlength="50" v-model.trim="row.totalDose" placeholder="请输入"></el-input>
                    <span v-else>{{ row.totalDose }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位">
                  <template v-slot="{ row }">
                    <el-select v-if="!isView" v-model="row.unit" filterable placeholder="请选择">
                      <el-option v-for="unit in unitOptions" :key="unit.value" :label="unit.label"
                        :value="unit.value"></el-option>
                    </el-select>
                    <span v-else>{{ row.unit }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="wayUse" min-width="100" label="使用途径">
                  <template v-slot="{ row }">
                    <el-select style="width: 100%" v-if="!isView" v-model="row.wayUse" multiple filterable collapse-tags collapse-tags-tooltip
                      placeholder="请选择">
                      <el-option v-for="item in wayUseOptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                    </el-select>
                    <span v-else>{{ row.wayUse.join(',') || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="singleDose" label="单次用量">
                  <template v-slot="{ row }">
                    <el-input v-if="!isView" class="formWidth" v-model.trim="row.singleDose" placeholder="请输入"
                      @input="()=>{row.singleDose=limitFloat(row.singleDose)}" 
                      @blur="()=>{row.singleDose=giveFloatMin(row.singleDose)}" />
                    <span v-else>{{ row.singleDose }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="frequencyUse" label="使用频率">
                  <template v-slot="{ row }">
                    <el-select v-if="!isView" v-model="row.frequencyUse" filterable placeholder="请选择">
                      <el-option v-for="item in frequencyUseOptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                    </el-select>
                    <span v-else>{{ row.frequencyUse }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="daysUse" label="使用天数">
                  <template v-slot="{ row }">
                    <el-input v-if="!isView" class="formWidth" v-model.trim="row.daysUse" placeholder="请输入" 
                      @input="()=>{row.daysUse=limitInt(row.daysUse)}"
                      @blur="()=>{row.daysUse=giveIntMin(row.daysUse)}"
                      />
                    <span v-else>{{ row.daysUse }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="baseInfo infoBox" style="margin-top: 8px;">
      <FormTitle titleName="自定义属性" style="margin-bottom: 16px;"></FormTitle>
      <el-form ref="customAttributeFormRef" label-width="auto">
        <el-row>
          <el-col :span="8" v-for="item in customAttribute" :key="item.extraAttributesId">
              <el-form-item :label="item.extraAttributesName">
                <template #label>
                  <div v-if="item.extraAttributesName.length<8" class="myLabel ellipsis">
                    {{ `${item.extraAttributesName}${isView?':':''}` }}
                  </div>
                  <el-tooltip
                    v-else
                    :content="item.extraAttributesName"
                    placement="top-start"
                  >
                    <div class="myLabel ellipsis">{{ `${item.extraAttributesName}${isView?':':''}` }}</div>
                  </el-tooltip>
                </template>
                <template v-if="!isView">
                  <el-input v-if="item.fieldType === 1" class="formWidth" v-model.trim="item.extraAttributesValue" :maxlength="100" placeholder="请输入"></el-input>
                  <el-input v-if="item.fieldType === 2" class="formWidth" v-model.trim="item.extraAttributesValue" @input="()=>{item.extraAttributesValue=limitFloat(item.extraAttributesValue)}" placeholder="请输入"></el-input>
                  <el-select v-if="item.fieldType === 3" v-model="item.extraAttributesValue" filterable placeholder="请选择" class="formWidth">
                    <el-option v-for="option in item.optionContent" :key="option" :label="option" :value="option"></el-option>
                  </el-select>
                  <el-select v-if="item.fieldType === 4" v-model="item.extraAttributesValue" multiple filterable collapse-tags collapse-tags-tooltip placeholder="请选择" class="formWidth">
                    <el-option v-for="option in item.optionContent" :key="option" :label="option" :value="option"></el-option>
                  </el-select>
                </template>
                <span v-else>{{ item.fieldType === 4 ? item.extraAttributesValue?.join(',') || '-' : textFilter(item.extraAttributesValue) }}</span>
              </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { useCommonData,getOptions } from '../Hooks/index'
import { pinyin } from 'pinyin-pro';
import FormTitle from '@/components/Form/FormTitle.vue'
import UploadImg from '@/components/UploadImg/index.vue'
import { baseInfoFormRules,minSalePriceRules } from './rules.js'
import { textFilter,limitFloat,limitInt,giveIntMin,giveFloatMin,limitMax } from '@/utils/common'
const props = defineProps({
  isView: {
    type: Boolean,
    default: false
  },
  customAttributes:{
    type: Array,
    default: () => []
  }
})
onBeforeMount(()=>{
  getOptions()
})
const formRef = ref()
// 表单数据
const form = ref({
  name: '',
  code: '',
  type: '',
  brand: [],
  barCode: '',
  mnemonicCode: '',
  specification: '',
  unit: '',
  placeOrigin: '',
  manufacturer: '',
  executiveStandard: '',
  imgs: [],
  salesClassification: [],
  salesStatus: 1,
  retailPrice: null,
  latestPurchasePrice: null,
  minSellingPrice:null,//最低售价
});
const categoryLabel = computed(()=>{
  return typeOptions.value.find(item => item.value === form.value.type)?.label || ''
})
const salesClassLabel = computed(()=>{
  return form.value.salesClassification.map(item => {
    return salesClassOptions.value.find(salesClass => salesClass.value === item)?.label ?? ''
  }).join(',') || ''
})
const customAttributeFormRef = ref()

const {
  typeOptions,
  brandOptions,
  unitOptions,
  salesClassOptions,
  wayUseOptions,
  frequencyUseOptions,
} = useCommonData()

const customAttribute = ref([])
const emits = defineEmits(['update:customAttributes','changeSalesStatus'])
watch(()=>props.customAttributes,(newVal)=>{
  customAttribute.value = newVal
})
watch(customAttribute,(newVal)=>{
  emits('update:customAttributes',newVal)
},{
  deep:true
})

const formatBrand = (brands)=>{
  return brandOptions.value.filter(item=>brands.includes(item.value)).map(item=>item.label).join(',')
}

const tableData = ref([
  {
    totalDose: '',
    unit: '',
    wayUse: [],
    frequencyUse: '',
    singleDose: null,
    daysUse: null
  }
])
const backValueImg = (val) => {
  form.value.imgs = val;
  formRef.value.validateField('imgs');
}

const nameBlur = ()=>{
  if(form.value.name){
    formRef.value.validateField('mnemonicCode');
  }
}
const nameInput = (val) => {
  const reg = /[\u4e00-\u9fa5]/g
  const py = val.replace(reg, (match)=>{
    return pinyin(match, {
      toneType: 'none', // 设置拼音风格
      separator: '',
      pattern:'first',
    }).toLocaleUpperCase();
  })
  form.value.mnemonicCode = py
}
const changeSalesStatus = (val) => {
  emits('changeSalesStatus', val)
}

const reset = ()=>{
  formRef.value.resetFields()
  // customAttributeFormRef.value.resetFields()
  customAttribute.value = []
  
  form.value = {
    name: '',
    code: '',
    type: '',
    brand: [],
    barCode: '',
    mnemonicCode: '',
    specification: '',
    unit: '',
    placeOrigin: '',
    manufacturer: '',
    executiveStandard: '',
    imgs: [],
    salesClassification: [],
    salesStatus: 1,
    retailPrice: null,
    latestPurchasePrice: null,
    minSellingPrice:'',//最低售价
  }
  tableData.value = [
    {
      totalDose: '',
      unit: '',
      wayUse: [],
      frequencyUse: '',
      singleDose: null,
      daysUse: null
    }
  ]
}

// 零售价失焦
const blurRetailPrice = ()=>{
    form.value.retailPrice=giveFloatMin(form.value.retailPrice)
    if(form.value.minSellingPrice){
      formRef.value.validateField(['minSellingPrice'])
    }
  }
defineExpose({
  formRef,
  form,
  reset,
  usage: tableData.value[0],
  tableData,
  categoryLabel,
  salesClassLabel
})
</script>

<style lang="less" scoped>
.infoBox {
  margin-top: 24px;
}

.formWidth {
  width: 80%;
}

.tips {
  color: #666;
  font-size: 12px;
  width: 450px;
}
.imgBox{
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  .imgItemBox{
    width: 160px;
    height: 160px;
    border-radius: 16px;
    border: 1px solid #DDD;
  }
}
.myLabel{
  max-width: 110px;

}
</style>